package o.mrs;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;


public class FindPerson extends Activity{

		private EditText find;
		private Button boton;
		private ListView lista;
	   
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.findperson);
	       	    
	        find=(EditText) findViewById(R.id.findP);  
	        boton=(Button) findViewById(R.id.findButton);
	        lista=(ListView) findViewById(R.id.findList); 
	        
	        boton.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					 try {
						String strJson = ApiRest.getRequestGet("patient/?q=" + find.getText().toString());
						JSONObject jsonObject = new JSONObject(strJson);
						JSONArray arrayResult = (JSONArray) jsonObject.get("results");
						
						String[] listPatient = new  String[arrayResult.length()];
						final String[] listUuid = new  String[arrayResult.length()];
						for(int contador=0; contador < arrayResult.length(); contador ++){
							JSONObject registro = (JSONObject) arrayResult.get(contador);							
							listPatient[contador]=(String) registro.get("display");
							listUuid[contador]=(String) registro.get("uuid");
											
						}
						 ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,listPatient); 	
						 lista.setAdapter(adapter);
						 
						 lista.setOnItemClickListener(new OnItemClickListener() {
				         	 
								public void onItemClick(AdapterView<?> parent, View view, int posicion, long id) {
									//Toast.makeText(getApplicationContext(),listUuid[posicion], Toast.LENGTH_SHORT).show();	
									
									Intent i = new Intent();
									i.putExtra("URI",listUuid[posicion]);
									i.setClass(getApplicationContext(),Encounter.class);	
									startActivity(i);
								}
				         });	
						 
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});
	       
	        
	    }
	
}
